<?php
// $Id$

/**
 * Controller_Admin_Rate 控制器
 */
class Controller_Admin_Rate extends Controller_Abstract
{
	function _format_appendSql()
	{
		$append = array();
		if (isset($_SESSION['acct']))
// 		{
// 			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
// 			{
// 			//为管理
					
// 			}else
// 			{
// 				//$append['admin_id'] = $_SESSION['acct']['admin_id'];
// 				$append['agent_id'] = Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']);
// 				
// 			}
			$append['agent_id'][] = $_SESSION['acct']['id'];
//		}
		return $append;
	}
	/**
	 * 
	 * 代理费率组
	 */
	function actionagent()
	{

		$this->union_table = Rategroup::meta();
		$this->lists($this->_format_appendSql());//array('agent_id'=>$_SESSION['acct']['id'])
		//$this->_view['agent_list'] = Acct::_get_arrayinfo();
	}
	function actiongroupadd()
	{
		$this->union_table = Rategroup::meta();
		//ini_set('allow_call_time_pass_reference', true); //开启引用？
		$handle = new helper_autoinsert($this->union_table);
		$form = new form_rate_groupadd(url($this->_context->controller_name.'/'.$this->_context->action_name));

		$result = $handle->add($form, 'id',$_GET);
		
		if ($this->_context->isGET())
		{
		//	$result->element('agent_id')->items = array_merge(array($_SESSION['acct']['id']=>'请选择一个代理'),Acct::_get_arrayinfo($this->_format_appendSql()));
			
		//	$param = Acct::_get_arrayinfo($this->_format_appendSql());
			//$param[$_SESSION['acct']['id']] = $_SESSION['acct']['acctname'];
			//$result->element('agent_id')->items = $param;
			$this->_view['form'] = $result;
			$this->_viewname = '../form/add';
		}else {
			Syslog::logs('编辑费率组:'.$_POST['rategroupname']);
			return call_user_func_array(array($this,$handle->status),array($result));
		}
	}
	function actiongroupdel()
	{
		Syslog::logs('删除费率组:'.$this->_context->ids);
		$this->union_table = Rategroup::meta();
	    Rate::meta()->deleteWhere(array_merge($this->_format_appendSql(),array('rategroupid'=>$this->_context->ids)));
		$this->delete(array_merge($this->_format_appendSql(),array('id'=>$this->_context->ids)));
	}
	/**
	 * 费率上穿
	 */
	function actionrateexp()
	{
		if ($this->_context->isGET())
		{
			$form = new Form_rate_exp(url($this->_context->controller_name.'/'.$this->_context->action_name));
			$form->element('rategroupid')->value =  intval($this->_context->rategroupid);
			$this->_view['form'] = $form;
			$this->_viewname = '../rate/rateexp';
		}else
		{
			//add users
			
			$userfile = isset($this->_context->cardfile)?trim($this->_context->cardfile):'';
			if (is_file($userfile))
			{
				//post
				$card = array(
						'agent_id'=>intval($_SESSION['acct']['id']),
						'rategroupid'=>intval($this->_context->rategroupid)
				);
		
				$handle = fopen($userfile, 'r');
				if($handle)
				{
					$split_char = ',';
					$i = 0;
					$ok = 0;
					$no = 0;
					$line_num = 0;
					$err_line = '';
					while (!feof($handle))
					{
						$line_num +=1;
						$lineCard = fgets($handle,400);
						$Split_arr = explode($split_char, $lineCard);
						if(QValidator::validate_between(count($Split_arr), 4, 5))
						{
							if(strlen($Split_arr[0])>0 && strlen($Split_arr[1])>0 && strlen($Split_arr[2])>0 && strlen($Split_arr[3])>0 )
							{
								$time = explode( '-',$Split_arr[3]);
								$card['prefix'] = trim($Split_arr[0]);
								$card['prefixname'] = trim($Split_arr[1]);
								$card['rateprice'] = floatval($Split_arr[2]);
								$card['start_hour'] = $time[0];
								$card['end_hour'] = $time[1];
								$card['payunitsecond'] = intval($Split_arr[4]) ? intval($Split_arr[4]):6;
								
								$vouch = Rate::find('agent_id = ? and prefix = ? and rategroupid = ?',intval($_SESSION['acct']['id']),$Split_arr[0],intval($this->_context->rategroupid))->getOne();
								//$user = Acct::find('acctname = ?',$userArr['acctname'])->getOne();
								if($vouch->id())
								{
									$err_line .= ','.$line_num;
								}else
								{
									try {
										$vouch = new Rate($card);
										$vouch->save(0,'create');
										$ok +=1;
									} catch (Exception $e) {
										$err_line .= ','.$line_num;
									}
								}
							}else
							{
								$no +=1;
								$err_line .= ','.$line_num;
								continue;
							}
						}else
						{
							$no +=1;
							$err_line .= ','.$line_num;
							continue;
						}
					}
					fclose($handle);
					//删除文件
					//@unlink($userfile);
					Syslog::logs('导入费率:'.$ok.'条数据');
					return $this->success(sprintf('成功导入%d条记录，失败%d条，分别存在:%s',$ok,$no,$err_line));
				}else
				{
					return $this->error('文件打开失败');
				}
			}else
			{
				return $this->error('文件不存在,请重新上传');
			}
		
		}
		
	}
	
	function actionrateset()
	{
		$ids = trim($this->_context->ids);
		$bili = floatval($this->_context->bili);
		$rategroupid = intval($this->_context->rategroupid);
		$agent_id = intval($_SESSION['acct']['id']);
		$ids = explode(',', $ids);
		unset($ids[0]);
		$param['agent_id']=$agent_id;
		$param['rategroupid'] = $rategroupid;
		$param['id'] = $ids;
		$list = Rate::find($param)->getAll();
		
		foreach ($list as $k=>$v)
		{
			$v->rateprice = $v->rateprice * $bili;
			$v->save(0,'update');
		}
		exit('批量修改价格成功');
	}
	function actionratelist()
	{
		$this->union_table = Rate::meta();
		$this->lists(array_merge(array('rategroupid'=>$this->_context->rategroupid),$this->_format_appendSql()));
	}
	function actionrateadd()
	{
		$this->union_table = Rate::meta();
		$handle = new helper_autoinsert($this->union_table);
		$form = new Form_rate_rateadd(url($this->_context->controller_name.'/'.$this->_context->action_name));
		$result = $handle->add($form, 'id',$_GET);
		if(intval($this->_context->payunitsecond) <= 1 && $this->_context->isPOST())
		{
			return $this->error('默认周期应该>=1秒');
			die;
		}
		if($this->_context->rategroupid)
		{
			$only = Rategroup::find('id = ? and agent_id = ?',intval($this->_context->rategroupid),$_SESSION['acct']['id'])->getCount('id');
			if($only <= 0)
			{
				return $this->error('对不起,您不能编辑此数据');
				die;
			}
			
		}
		
		if ($this->_context->isGET())
		{
			//添加 编辑时候 默认所属代理
		//	$result->element('agent_id')->items = $_SESSION['acct']['id'];
			$this->_view['form'] = $result;
			$this->_viewname = '../form/add';
		}else {
			Syslog::logs('编辑费率:'.$_POST['prefixname']);
			return call_user_func_array(array($this,$handle->status),array($result));
		}
	}
	function actionratedel()
	{
		Syslog::logs('删除费率:'.$this->_context->ids);
	$this->union_table = Rate::meta();
	$this->delete(array_merge($this->_format_appendSql(),array('id'=>$this->_context->ids)));
	}
	
}


